<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-17px"
      @submit.prevent="handleQuery"
    >
      <el-form-item label="项目名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-220px"
          placeholder="请输入项目名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程阶段" prop="stage">
        <el-select
          v-model="queryParams.stage"
          class="!w-220px"
          placeholder="请选择流程阶段"
          @change="handleQuery"
          placement="bottom"
        >
          <el-option v-for="item in stageList" :key="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          @change="handleQuery"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      :data="list"
      v-loading="loading"
      empty-text="暂无记录"
      element-loading-text="Loading..."
      stripe
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      show-overflow-tooltip
    >
      <el-table-column align="center" label="项目化核算编码" prop="project_code" width="160">
        <template #default="{ row }">
          {{ !row.project_code ? '--' : row.project_code }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目名称" prop="project_name" min-width="200">
        <template #default="{ row }">
          {{ !row.project_name ? '--' : row.project_name }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="流程阶段" prop="process_instance.name" min-width="120">
        <template #default="scope">
          <div class="flex justify-center">
            <el-tag effect="light">{{ scope.row.process_instance.name }} </el-tag>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="当前任务" prop="name" min-width="120" /> -->
      <el-table-column align="center" label="当前任务" prop="name" min-width="120">
        <template #default="scope">
          <div class="flex justify-center">
            <el-tag effect="light">{{ scope.row.name }} </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="发起人"
        prop="process_instance.startUser.nickname"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="create_time"
        min-width="200"
      />
      <el-table-column align="center" label="操作" fixed="right" width="100">
        <template #default="scope">
          <el-button link type="primary" @click="handleAudit(scope.row)">处理</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="mt-35px text-14px"
      v-model:current-page="queryParams.pageNo"
      :hide-on-single-page="value"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      background
      layout="total,sizes,prev, pager, next,jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import * as KmsApi from '@/api/project/kms'
import * as BpmApi from '@/api/project/bpm'
import { useRouter } from 'vue-router'
import { dateFormatter } from '@/utils/formatTime'
import dayjs from 'dayjs'
import { ref, reactive, onMounted } from 'vue'

const { push } = useRouter() // 路由
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const Alllist = ref([]) // 总数据
const value = ref(true)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  stage: '',
  createTime: []
})

const stageList = ref([])

const queryFormRef = ref()

// 条数变化
const handleSizeChange = (e) => {
  queryParams.pageSize = e
  queryParams.pageNo = 1
  getList()
}

// 页码变化
const handleCurrentChange = (e) => {
  queryParams.pageNo = e
  getList()
}
// 数据分页
const listcheck = () => {
  list.value = Alllist.value.slice(
    (queryParams.pageNo - 1) * queryParams.pageSize,
    queryParams.pageNo * queryParams.pageSize
  )
  if (list.value.length === 0) {
    value.value = true
  } else {
    value.value = false
  }
}

// 查询任务列表
const getList = async () => {
  return new Promise<void>((resolve, reject) => {
    BpmApi.getMytodoList()
      .then((res: { list: any }) => {
        const data = reactive(res.list)
        loading.value = false
        const projectList = ref([])
        data.forEach((item: { process_instance: { businessKey: any } }) => {
          const projectCode = item.process_instance.businessKey.split('+')[0]
          projectList.value.push(projectCode)
        })
        if (projectList.value.length > 0) {
          // 批量获取项目名称
          const projectsData = {
            project_codes: [...projectList.value]
          }
          KmsApi.getProjectsByList(projectsData)
            .then((res) => {
              let newdata = reactive(res)
              data.forEach(
                (item: {
                  process_instance: { businessKey: string | number; name: any }
                  project_name: any
                }) => {
                  const projectCode = item.process_instance.businessKey.split('+')[0]
                  if (newdata[projectCode]) {
                    item.project_code = projectCode
                    item.project_name = newdata[projectCode].project_name
                    // stageList.value.push(item.process_instance.name)
                  }
                  stageList.value.push(item.process_instance.name)
                }
              )
              stageList.value = [...new Set(stageList.value)]
              Alllist.value = data
              total.value = data.length
              listcheck()
              resolve()
            })
            .catch((error) => {
              reject(error)
            })
        }
      })
      .catch((error) => {
        loading.value = false
        reject(error)
      })
  })
}

// 搜索按钮操作
const handleQuery = async () => {
  queryParams.pageNo = 1
  await getList()

  // 转换日期范围为 dayjs 对象
  const [startDate, endDate] = (queryParams.createTime || []).map((date) => dayjs(date))

  // 过滤函数
  const filterList = (list) => {
    return list.filter((item) => {
      const projectNameMatches = !queryParams.name || item.project_name?.includes(queryParams.name)
      const stageMatches =
        !queryParams.stage || item.process_instance.name?.includes(queryParams.stage)
      const createTimeMatches =
        !startDate ||
        !endDate ||
        (item.create_time >= startDate.startOf('day').valueOf() &&
          item.create_time <= endDate.endOf('day').valueOf())
      return projectNameMatches && stageMatches && createTimeMatches
    })
  }

  Alllist.value = filterList(Alllist.value)
  total.value = Alllist.value.length
  listcheck()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.pageNo = 1
  getList()
}

// 处理审批按钮跳转项目移交详情
const handleAudit = (row: any) => {
  if (row.process_instance.name === '项目变更') {
    push({
      name: 'ProjectChangeApproval',
      query: {
        project_code: row.process_instance.businessKey.split('+')[0],
        change_key: row.process_instance.businessKey.split('+')[1],
        process_instance_id: row.process_instance_id
      }
    })
  } else {
    push({
      name: 'ProjectDetails',
      query: {
        project_code: row.process_instance.businessKey
      }
    })
  }
}

// 初始化
onMounted(() => {
  getList()
})
</script>
<style scoped>
.el-pagination {
  justify-content: flex-end;
}
</style>